package com.example.customconfig.config;

import com.example.customconfig.properties.HelloServiceProperties;
import com.example.customconfig.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author ljw
 * @description 根据此类的存在与否来创建 HelloService 的 Bean,这个类可以是第三方内库的类
 * @date 2021/10/12 8:00
 */
@Configuration
//开启属性注入，将配置类声明成 Bean ,使用 @Autowired 引入（在配置类加 @Component 直接声明成 Bean ，效果一样）
@EnableConfigurationProperties(HelloServiceProperties.class)
//内路径下存在对应类的条件下
@ConditionalOnClass(HelloService.class)
//配置中存在 hello.enabled=enabled 的情况下，matchIfMissing = true 作用是如果没有设置默认为true，即条件符合
@ConditionalOnProperty(prefix = "hello", value = "enabled", matchIfMissing = true)
public class HelloServiceAutoConfiguration {

    //注入配置 Bean
    @Autowired
    private HelloServiceProperties helloServiceProperties;

    @Bean
    //当容器中没有这个 Bean 时新建 Bean
    @ConditionalOnMissingBean(HelloService.class)
    public HelloService helloService() {
        HelloService helloService = new HelloService();
        helloService.setMsg(helloServiceProperties.getMsg());
        return helloService;
    }
}
